package com.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

public class HttpClientUtils {
	       
	// 创建HttpClientBuilder
	 static HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
	// HttpClient
	 private static CloseableHttpClient closeableHttpClient;
	 static{
		 Header hander = new BasicHeader("X-RTCAT-APIKEY", "aff5a45c-5f9f-495c-a62a-b19f0f4ccc04");
		 Header hande2 = new BasicHeader("X-RTCAT-SECRET", "20a3f17f-b535-4464-987a-f1a56556b95e");
		 List<Header> handers = new ArrayList<Header>();
		 handers.add(hander);
		 handers.add(hande2);
		 httpClientBuilder.setDefaultHeaders(handers);
		 
	 }
	 public HttpClientUtils(){
		 
	 }
	 
	
	 public static String getData(String url,Map<String, Object> param){
		 int i=0;
		 if (param!=null) {
			 Set<String> sets = param.keySet();
			 Iterator<String>  iteator =  sets.iterator();
			 while (iteator.hasNext()) {
			   String key  =	 iteator.next();
			   if (i==0) {
				   url+="?"+key+"="+param.get(key);
			   }else {
				   url+="&"+key+"="+param.get(key);
			   }
			   i++;
			}
		}
		
		 HttpGet httpGet = new HttpGet(url);
		 closeableHttpClient = httpClientBuilder.build();
		 try {
			// 执行get请求
			HttpResponse httpResponse = closeableHttpClient.execute(httpGet);
//			// 获取响应消息实体
			HttpEntity entity = httpResponse.getEntity();
		
			System.out.println(EntityUtils.toString(entity));
			return entity.toString();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 return null;
	 }
	
	 
}

